package org.practice.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.practice.dao.DaoFactory;
import org.practice.dao.UserDao;
import org.practice.form.LoginForm;
import org.practice.model.User;
import org.practice.util.Constant;
import org.practice.util.CookieUtil;

public class LoginAction extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		LoginForm lf=(LoginForm)form;
		String email=lf.getEmail();
		String password=lf.getPassword();
		//访问DAO
		UserDao dao=DaoFactory.createUserDao();
		User user=dao.validateUser(email, password);
		if(user==null){
			ActionMessages errors=new ActionMessages();
			errors.add("error.verfity.user",new ActionMessage("error.verify.user"));
			this.saveErrors(request, errors);
			return mapping.findForward("fail");
		}else if(user.isVerify()){
			//user对象通过email验证之后，可以将user对象的信息缓存在session，并且把user对象的
			//id信息通过cookie保存在Client Browser
			HttpSession session =request.getSession();
			session.setAttribute(Constant.SESSION_KEY_USER,user);
			CookieUtil.addCookie(response, Constant.COOKIE_KEY_USERID, 
					String.valueOf(user.getId()));
			return mapping.findForward("success");
		}else{
			return mapping.findForward("verify");
		}
		
	}
	
}
